# -*- encoding: utf-8 -*-
'''
Manage use of email to report errors in the server

Requires a configuration section, for example:

class administration:
    error_email             = '.. target email for reports ..'
    sendmail_location       = '/path/to/sendmail'
    origin_email            = '.. origin email for reports ..'
'''
import datetime, traceback
from pprint import pprint
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
from cStringIO import StringIO

SEPERATOR = '------------------------- %s -------------------------------'

from akara import request, module_config as config, response

class error_reporting(object):
    def __init__(self):
        self.error_email         = config().get('error_email')
        self.sendmail_location   = config().get('sendmail_location')
        self.origin_email        = config().get('origin_email')

    def __call__(self, func):
        if self.sendmail_location and self.error_email:
            def innerHandler(*args, **kwds):
                if '_' in kwds:
                    del kwds['_']
                try:
                    return func(*args, **kwds)
                except Exception, e:
                    dt_str = datetime.datetime.now().strftime(
                        "%A, %d. %B %Y %I:%M %p"
                    )

                    st = StringIO()
                    traceback.print_exc(file=st)
                    pprint(request.environ,st)

                    request_body = ''
                    input_file = request.environ.get('wsgi.input')
                    if input_file is not None:
                        try:
                            request_body = input_file.read()
                        except: pass

                    body = '\n'.join([dt_str,
                                      SEPERATOR%"Traceback and request content",
                                      st.getvalue(),
                                      SEPERATOR%"Request body",
                                      request_body])

                    msg = MIMEText(body)
                    msg["From"] = self.origin_email
                    msg["To"] = self.error_email
                    msg["Subject"
                    ] = "Uncaught exception on Akamu / Akara server: %s"%e
                    p = Popen([self.sendmail_location, "-t"], stdin=PIPE)
                    p.communicate(msg.as_string())
                    print msg.as_string()
                    raise e
            return innerHandler
        else:
            return func